#include "StdAfx.h"
#include "ReflectingObject.h"

ReflectingObject::ReflectingObject(void)
{
}

ReflectingObject::~ReflectingObject(void)
{
}

int ReflectingObject::Load(char* file_nfg, Skydome* skydome)
{
	//==================Load model
	if (model.Load(file_nfg) == LOAD_FAILED)
		return LOAD_FAILED;

	texture_id = skydome->texture_id;

	
	glGenBuffers(1, &vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	glBufferData(GL_ARRAY_BUFFER, model.num_vertices * sizeof(Vertex), model.vertices, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);

	glGenBuffers(1, &ibo);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, model.num_indices * sizeof(GLushort), model.indices, GL_STATIC_DRAW);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	
	myShaders.Init("../Resources/Shaders/ReflectionShaderVS.vs", "../Resources/Shaders/ReflectionShaderFS.fs");

	return LOAD_SUCCEEDED;
}

void ReflectingObject::Draw( ESContext *esContext, Camera* camera)
{
	glUseProgram(myShaders.program);
	// Open buffer
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);

	// Pass Vertex to Shaders
	glEnableVertexAttribArray(myShaders.positionAttribute);
	glVertexAttribPointer(myShaders.positionAttribute, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);

	// Pass norm to Shaders
	glEnableVertexAttribArray(myShaders.normalAttribute);
	glVertexAttribPointer(myShaders.normalAttribute, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (char*) 0 + 2 * sizeof(Vector3) + sizeof(Vector2) + sizeof(Vector4));


	// Pass Texture
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_CUBE_MAP, texture_id);
	glUniform1i(myShaders.textureUniform, 0);
	// Pass Camera Position
	Vector3 pos = camera->getPosition();
	glUniform3f(myShaders.cameraPositionUniform, pos.x, pos.y, pos.z);
	// Pass MVP Matrix
	Matrix mvp =  getWorldMatrix() * camera->getViewMatrix() * camera->getProjectionMatrix();
	glUniformMatrix4fv(myShaders.matMVPUniform, 1, GL_FALSE, &(mvp.m[0][0]));
	// Pass World Matrix
	glUniformMatrix4fv(myShaders.matWorldUniform, 1, GL_FALSE, &(getWorldMatrix().m[0][0]));

	// Pass Index
	int size;
	glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);

	// Draw
	glDrawElements(GL_TRIANGLES, size / sizeof(GLushort), GL_UNSIGNED_SHORT, 0);

	// Release buffer
	glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}


void ReflectingObject::Update ( ESContext *esContext, float deltaTime)
{}